"""
Copyright (c) 2024 [XKW.Beijing]
All rights reserved.

Author: [tangxiaojun]
Email: [417281862@qq.com]

"""
import configparser

from flask import request, g, Response
import functools
import base64


class HttpBasicAuthMiddleware:
    def __init__(self):
        # 读取所有配置文件
        config = configparser.ConfigParser()
        config.read('app.ini')

        apps = []
        for section in config.sections():
            # 将每个section的配置项转换为字典，并添加到列表中
            app_enable = config.getboolean(section, 'enable')
            if app_enable:
                app = {
                    'app_id': config.get(section, 'app_id'),
                    'app_secret': config.get(section, 'app_secret'),
                    'enable': config.getboolean(section, 'enable'),
                    'auth': base64.b64encode(f"{config.get(section, 'app_id')}:{config.get(section, 'app_secret')}".encode()).decode()
                }
                apps.append(app)
        print(apps)
        self.apps = apps

    def init_app(self, app):
        app.before_request(self.authenticate)
        # app.after_request(self.after_request)

    def verify_func(self, auth):
        for app in self.apps:
            if app['auth'] == auth:
                return True

    def authenticate(self):
        auth_info = request.headers['Authorization']
        if not (auth_info and self.verify_func(auth_info)):
            return Response(
                '非法请求，请联系管理员.\n',
                401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'}
            )
